package com.hxut.service.impl;

import com.hxut.entity.AccountUser;
import com.hxut.entity.SysUser;
import com.hxut.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Objects;

/**
 * description: UserDetailServiceImpl
 * date: 2022/7/10 12:25
 * author: MR.孙
 */

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户信息
        SysUser sysUser=sysUserService.getByUsername(username);
        if(Objects.isNull(sysUser)){
            throw new UsernameNotFoundException("用户名或密码不正确");
        }

        return new AccountUser(sysUser.getId(),sysUser.getUsername(),sysUser.getPassword(),getAuthentication(sysUser.getId()));
    }

    /**
     * @description: 获取用户权限信息(角色、菜单权限)
     * @param userId
     * @return: java.util.List<org.springframework.security.core.GrantedAuthority>
     * @author: MR.孙
     * @date: 2022/7/10 13:18
    */
    public List<GrantedAuthority> getAuthentication(Long userId) {
        //角色(ROLE_admin)、菜单操作权限sys:user:list
        String authority=sysUserService
                .getAuthorityInfo(userId);//ROLE_admin,ROLE_normal,sys:user:list..
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
